package com.dnjn.mes.common.ext.mybatis;

import com.dnjn.mes.common.ext.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
public class MybatisRedisCache implements Cache {
    private final String prefix = "mybatis:cache:";

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    private String id;
    private static int cacheSec;

    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("cache instances require an ID");
        }
        log.info("mybatis cache name: {}", id);
        this.id = id;
    }

    public static void setCacheSec(int cacheSec) {
        MybatisRedisCache.cacheSec = cacheSec;
    }

    protected RedisTemplate<String, Object> redisTemplate() {
        return SpringContextHolder.getBean("redisTemplate");
    }


    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (value == null) {
            return;
        }
        if (cacheSec > 0) {
            redisTemplate().opsForValue().set(prefix + key.toString(), value, cacheSec, TimeUnit.SECONDS);
        } else {
            redisTemplate().opsForValue().set(prefix + key.toString(), value);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            if (key != null) {
                return redisTemplate().opsForValue().get(prefix + key.toString());
            }
        } catch (Exception e) {
            log.error("缓存出错 ");
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        if (key != null) {
            redisTemplate().delete(prefix + key.toString());
        }
        return null;
    }

    @Override
    public void clear() {
        log.debug("清空缓存");

        Set<String> keys = redisTemplate().keys("*:" + this.id + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate().delete(keys);
        }
    }

    @Override
    public int getSize() {
        //return getRedisTemplate().opsForHash().size(id).intValue();
        /* Long size = redisTemplate().execute((RedisCallback<Long>) RedisServerCommands::dbSize);
        return size.intValue();*/

        Set<String> keys = redisTemplate().keys(prefix + "*");
        if (CollectionUtils.isNotEmpty(keys)) {
            return keys.size();
        }
        return 0;


    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}
